<template>
  <div class="auth-container">
    <div class="auth-card" style="width: 400px; padding: 40px;">
      <div class="auth-header">
        <div class="auth-logo">
          <el-icon><Lock /></el-icon>
        </div>
        <h1 class="auth-title">找回密码</h1>
      </div>
      
      <el-form 
        :model="forgotForm" 
        :rules="rules"
        ref="forgotFormRef"
        class="auth-form"
        @submit.prevent="handleSubmit"
      >
        <el-form-item prop="role">
          <el-select 
            v-model="forgotForm.role" 
            placeholder="请选择您的身份"
            size="large"
            style="width: 100%"
          >
            <el-option label="患者" value="patient" />
            <el-option label="医生" value="doctor" />
            <el-option label="医院管理员" value="admin" />
          </el-select>
        </el-form-item>
        
        <el-form-item prop="phone">
          <el-input 
            v-model="forgotForm.phone" 
            placeholder="请输入手机号"
            prefix-icon="Iphone"
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="code">
          <div class="code-input">
            <el-input 
              v-model="forgotForm.code" 
              placeholder="请输入验证码"
              prefix-icon="Key"
              size="large"
            />
            <el-button 
              class="send-code-btn" 
              :disabled="isCountingDown"
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item prop="newPassword">
          <el-input 
            v-model="forgotForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="forgotForm.confirmPassword" 
            type="password" 
            placeholder="请确认新密码"
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="auth-btn"
            native-type="submit"
            :loading="loading"
          >
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="auth-footer">
        <el-link type="primary" @click="$router.push('/login')">
          <el-icon><ArrowLeft /></el-icon>
          返回登录
        </el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock, Iphone, Key, ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()
const forgotFormRef = ref()

const forgotForm = reactive({
  role: '',
  phone: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== forgotForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const rules = {
  role: [
    { required: true, message: '请选择您的身份', trigger: 'change' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ]
}

const loading = ref(false)
const countdown = ref(0)
const isCountingDown = ref(false)
let countdownTimer = null

const sendVerificationCode = () => {
  // 验证角色和手机号
  if (!forgotForm.role) {
    ElMessage.error('请先选择您的身份')
    return
  }
  
  forgotFormRef.value.validateField('phone', (valid) => {
    if (!valid) return
    
    // 模拟发送验证码
    isCountingDown.value = true
    countdown.value = 60
    
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer)
        isCountingDown.value = false
      }
    }, 1000)
    
    ElMessage.success(`验证码已发送至 ${forgotForm.phone}`)
  })
}

const handleSubmit = () => {
  forgotFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      // 模拟API调用，根据角色不同可能有不同处理
      let apiEndpoint = ''
      switch(forgotForm.role) {
        case 'patient':
          apiEndpoint = '/api/patient/reset-password'
          break
        case 'doctor':
          apiEndpoint = '/api/doctor/reset-password'
          break
        case 'admin':
          apiEndpoint = '/api/admin/reset-password'
          break
      }
      
      // 这里应该是实际的API调用
      console.log(`调用${apiEndpoint}重置密码`)
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      ElMessage.success('密码重置成功，请使用新密码登录')
      router.push('/login')
    } catch (error) {
      console.error('重置密码错误:', error)
      ElMessage.error('重置密码失败，请稍后再试')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.auth-logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
  background: #000;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.auth-logo .el-icon {
  font-size: 36px;
  color: #00c0a5;
}

.auth-title {
  font-size: 24px;
  font-weight: 600;
  color: #000;
  margin: 0;
  text-align: center;
}

.auth-form {
  margin-bottom: 20px;
}

.auth-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  background-color: #1e5799;
  border: none;
  transition: background-color 0.3s;
}

.auth-btn:hover {
  background-color: #163f70;
}

.auth-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.code-input {
  display: flex;
  width: 100%;
  gap: 10px;
}

.send-code-btn {
  width: 140px;
  flex-shrink: 0;
}

.auth-footer .el-link {
  display: inline-flex;
  align-items: center;
  gap: 5px;
}
</style>